<?php defined ( 'SYSPATH' ) or die ( 'No direct script access.' );

class Controller_Resource extends Controller
{
	public function action_media()
	{
		// Get the file path from the request
		$file = $this->request->param ( 'file' );
		
		$type = $this->request->param ( 'type' );
		
		// Find the file extension
		$ext = pathinfo ( $file, PATHINFO_EXTENSION );
		
		// Remove the extension from the filename
		$file = substr ( $file, 0, - (strlen ( $ext ) + 1) );
		
		if (in_array($type,array('js','css','image'))){
			$dir = 'media/'.$type.'/';
		}else{
			$dir = 'media/';
		}
		
		if (is_file($file = $dir.$file.'.'.$ext))
		{
			// Send the file content as the response
			//$this->request->response = file_get_contents ( $file );
			$this->response->body(file_get_contents ( $file ));
		}
		else
		{
			// Return a 404 status
			$this->request->status = 404;
		}
		
		// Set the content type for this extension
		$this->request->headers ['Content-Type'] = File::mime_by_ext ( $ext );
	}
	
	
	public function action_uploadfile()
	{
		// Get the file path from the request
		$file = $this->request->param ( 'file' );
		
		// Find the file extension
		$ext = pathinfo ( $file, PATHINFO_EXTENSION );
		
		// Remove the extension from the filename
		$file = substr ( $file, 0, - (strlen ( $ext ) + 1) );
		
		$dir = 'uploadFile/';
		
		//if ($file = Kohana::find_file ( 'uploadFile', $file, $ext ))
		if (is_file($file = $dir.$file.'.'.$ext))
		{
            
			// Send the file content as the response
			//$this->request->response = file_get_contents ( $file );
			//echo "<script>location.href='/".$file."'</script>";
			//exit;
			header('Content-Description: File Transfer'); 
			header('Content-Type: application/octet-stream'); 
			header('Content-Disposition: attachment; filename='.basename($file)); 
			header('Content-Transfer-Encoding: binary'); 
			header('Expires: 0'); 
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
			header('Pragma: public'); 
			header('Content-Length: ' . filesize($file)); 
			ob_clean();
			flush();
			readfile($file);
			exit; 
			$this->response->body(file_get_contents ( $file ));
		}
		else
		{
			// Return a 404 status
			$this->request->status = 404;
			header('content-type:text/html;charset=utf8');
			die('找不到文件');
		}
		
		// Set the content type for this extension
		$this->request->headers ['Content-Type'] = File::mime_by_ext ( $ext );
	}
	
	public function action_html(){
		if ($rewrite = $this->request->param('id')){
			$rewrite = urldecode($rewrite);
			
			MON::connect(get_object_vars(project::config('conndb')));
			if (preg_match('/^[a-zA-Z0-9]+$/', $rewrite) && ($a = MON::factory('article',$rewrite))){
				if (strlen($a['rewrite']))
					lib_url::redirect(project::a_url($a));
			}else{
				$a = MON::factory('article')->findOne(array('rewrite'=>$rewrite));
				if (!$a)
	                __404();
	            //$a = Model::factory('tag')->tag2anchor($a);
			}
            
			//访问记录
			if ( (($ip = common::getip()) != '127.0.0.1')
				 && (stripos($_SERVER['HTTP_USER_AGENT'],'spider') === false)
				 && (stripos($_SERVER['HTTP_USER_AGENT'],'googlebot') === false)
				){
				MON::factory('view_record')->insert(array(
					'article_id'=>new MongoId($a['_id']),
					'rewrite'=>$rewrite,
					'ip'=>$ip,
					'HTTP_USER_AGENT'=>$_SERVER['HTTP_USER_AGENT'],
					'addTime'=>time()
				));
			}
			
			$smarty = m::factory('smarty');
			if (!$smarty->isCached('index.tpl',md5($rewrite))){
				$smarty->cache_lifetime = 3600*24*7;
				
				$tags = Model::factory('tag')->get_tags_anchor($a['_id'],'&nbsp;,',array('style'=>'padding:0px;float:none;display:inline;'));
				$comments = MON::factory('comment')->find(array('article_id'=>$a['_id']))->sort(array('addTime'=>-1));
				
				//配置文件
	        	$this->_config = project::config('common');
	        	
				$this->template = new lib_template();
	            
				//前一页
	            $referer = lib_url::HTTP_REFERER();
	            
	            //样式表直显
	            $this->template->style('media/css/common.css');
	            
	            //js直显
	            $this->template->endscript('media/js/default.js');
	            
	            //样式表
	            $this->template->css(array(
	            	'media/css/style.css'
	            ));
	            
	            //js
	            $this->template->js(array(
	            	'j/jquery-1.7.2.min.js',
	            	'j/common.js'
	            ));
	            $this->template->endjs(array(
	            	'j/cookie.js'
	            ));
	            
	            $this->template->title = $a['title'].project::config()->title;
	            $this->template->meta_keywords = strlen($a['keywords'])?$a['keywords']:$this->template->meta_keywords;
	            $this->template->meta_description = strlen($a['description'])?$a['description']:common::cutstr(str_replace('&nbsp;','',strip_tags(htmlspecialchars_decode($a['content']))),200);
	            
	            $this->template->main(View::factory('template/main'));
	            $this->template->head(View::factory('template/head'));
				$this->template->foot(View::factory('template/foot'));
				$this->template->extra(View::factory('template/extra'));
				$this->template->content_right(hook('sidebar'));
				
				View::set_global('base_url',lib_url::base());
				View::set_global('location_main',$this->request->controller());
				View::set_global('location_sub',$this->request->action());
				View::bind_global('object',$this);
	        	View::bind_global('referer',$referer);
	        	//提示信息
		        $message = lib_message::messageShow('front');
		        View::bind_global('message',$message);
		        
		        $smarty->assign('url',lib_url::get_url());
		        $smarty->assign('a',$a);
		        $smarty->assign('tags',$tags);
		        $smarty->assign('comments',$comments);
		        $smarty->assign('guestname',substr_replace($ip,'*',strrpos($ip,'.')+1));
		        $smarty->assign('xheditor',m::factory('xheditor',array('simple'=>true)));
		        
		        $this->template->content($smarty->fetch('a.tpl',md5($rewrite)));
		        
				$smarty->assign('template',$this->template->render());
			}
			
			$smarty->display('index.tpl',md5($rewrite));
		}
	}
	
} // End Welcome Controller
